<template>
  <div>
    <!-- 导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 视图区域 -->
    <el-card>
      <el-button type="primary" @click="addCate">添加分类</el-button>
      <!-- 表格 -->
      <tree-table
        class="tree-table"
        :data="CateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 是有有效 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i
        ></template>
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level == 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="editCate(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="deletCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 8]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCatedialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormrules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <!--级联选择器 -->
          <!-- options 指定数据源 -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChanges"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCates">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类信息 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editCatedialogVisible"
      width="50%"
    >
      <el-form
        :model="editCateForm"
        :rules="addCateFormrules"
        ref="editCateRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCatedialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveCateInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Cate",
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //商品列表
      CateList: [],
      total: 0,
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          template: "isOk",
        },
        {
          label: "排序",
          type: "template",
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          template: "opt",
        },
      ],
      //添加分类对话框
      addCatedialogVisible: false,
      //添加分类信息
      addCateForm: {
        //输入的分类名称
        cat_name: "",
        //父级分类的id
        cat_pid: 0,
        // 分类的等级
        cat_level: 0,
      },
      addCateFormrules: {
        cat_name: [
          {
            required: true,
            message: "请输入分类名称",
            trigger: "blur",
          },
        ],
      },
      //获得商品分类列表
      parentCateList: [],
      //指定级联数据对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 编辑分类信息对话框
      editCatedialogVisible: false,
      //编辑的分类信息
      editCateForm: {},
      // 选中的父级分类的ID数组
      selectedKeys: [],
    };
  },
  created() {
    this.getCategoriesList();
  },
  methods: {
    //获取商品列表
    async getCategoriesList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.err("请求商品列表失败");
      }
      this.CateList = res.data.result;
      this.total = res.data.total;
      console.log(this.CateList);
    },
    //监听页面尺寸的改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getCategoriesList();
    },
    //监听页面的变化
    handleCurrentChange(newpage) {
      this.queryInfo.pagenum = newpage;
      this.getCategoriesList();
    },
    // 点击按钮，展示添加商品分类对话框
    addCate() {
      //获取商品分类
      this.getParentCateList();
      this.addCatedialogVisible = true;
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.$message.err("请求商品分类失败");
      }
      //console.log(res.data);
      this.parentCateList = res.data;
    },
    //选中项发生变化时触发这个函数
    parentCateChanges() {
      //console.log(this.selectedKeys);
      // 如果selectedKeys数据的length大于零， 证明选中父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的id
        this.addCateForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1];
        //为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectedKeys.length;
        return;
      } else {
        this.addCateForm.cat_pid = 0;

        //为当前分类的等级赋值
        this.addCateForm.cat_level = 0;
      }
    },
    //点击按钮， 添加新的分类
    addCates() {
      //console.log(this.addCateForm);
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        //校验通过，发起请求
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          return this.$message.err("添加分类失败");
        }
        this.$message.success("添加分类成功");
        this.getCategoriesList();
        this.addCatedialogVisible = false;
      });
    },
    // 对话框关闭清空内容
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      // 清空选择框的内容
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    //编辑分类信息
    async editCate(cat_id) {
      //console.log(cat_id);
      const { data: res } = await this.$http.get("categories/" + cat_id);
      if (res.meta.status !== 200) {
        return this.$message.err("获取分类信息失败");
      }
      this.$message.success("获取分类信息成功");
      //console.log(res.data);
      this.editCateForm = res.data;
      this.editCatedialogVisible = true;
    },
    //点击确定修改分类信息
    saveCateInfo() {
      this.$refs.editCateRef.validate(async (valid) => {
        //校验表单信息
        if (!valid) return;
        //console.log(valid);
        //校验成功发起请求
        const { data: res } = await this.$http.put(
          "categories/" + this.editCateForm.cat_id,
          {
            cat_name: this.editCateForm.cat_name,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改分类信息失败");
        }
        this.editCatedialogVisible = false;
        this.getCategoriesList;
        this.$message.success("更新分类信息成功");
      });
    },
    //删除分类信息
    async deletCate(id) {
      const conformCateResoult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //确认删除， 返回的字符串为confirm
      //如果没有确认删除， 返回cancel
      //console.log(conformResoult);
      //console.log(conformCateResoult);
      if (conformCateResoult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      //删除分类
      const { data: res } = await this.$http.delete("categories/" + id);
      if (res.meta.status !== 200) {
        return this.$message.err("删除失败");
      }
      this.$message.success("删除成功");
      //更新用户列表
      this.getCategoriesList();
    },
  },
};
</script>

<style>
.tree-table {
  margin-top: 20px;
}
.el-cascader {
  width: 100%;
}
.el-cascader-menu {
  height: 200px;
}
</style>